<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">

          <a-col :md="8" :sm="24">
            <a-form-item label="优惠券名称">
              <a-input v-model="queryParam.couponName" placeholder="请输入"/>
            </a-form-item>
          </a-col>

<!--          <a-col :md="8" :sm="24">-->
<!--            <a-form-item label="上级机构">-->
<!--              <a-tree-select-->
<!--                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"-->
<!--                placeholder='请选择'-->
<!--                allowClear-->
<!--                treeDefaultExpandAll-->
<!--                :treeData="treeData"-->
<!--                v-model="queryParam.code"-->
<!--              >-->
<!--              <span style="color:#08c" slot="title" slot-scope="{key}"-->
<!--                    v-decorator="['key',{rules: [{ required: true, message: '请选择商户' }]}]">-->
<!--                {{value}}-->
<!--              </span>>-->
<!--              </a-tree-select>-->
<!--            </a-form-item>-->
<!--          </a-col>-->

          <template v-if="advanced">
            <a-col :md="8" :sm="24" >
              <a-form-item allowClear label="商圈" >
                <a-select v-model="queryParam.companyId" v-decorator="[ 'companyId']"  @change="handleProvinceChange">
                  <a-select-option v-for="item in companys" :key="item.id">{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24" >
              <!--<a-form-item label="商户">
                <a-select allowClear v-model="queryParam.merchantId" v-decorator="[ 'merchantId']">
                  <a-select-option v-for="item in merchantList" :key="item.id">{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>-->
              <a-form-item label="商户">
                <a-tree-select
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder='请选择商户'
                  allowClear
                  :treeData="treeData"
                  v-model="queryParam.code"
                >
                <span style="color:#08c" slot="title" slot-scope="{key}"
                      v-decorator="['key',{rules: [{ required: true, message: '请选择商户' }]}]">
                  {{code}}
                </span>
                </a-tree-select>
              </a-form-item>
            </a-col>
          </template>

          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button v-action:query type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button v-action:query style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
               <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd()">新建</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="{ show: true, clear: true }"
      :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
      :scroll="{ x: 1200 }"
    >
       <span slot="productPicUrl" slot-scope="text,record">
          <template>
               <img :src="record.productPicUrl" alt="" style="width: 100px;height: auto;">
        </template>
      </span>
      <span slot="value" slot-scope="text">
        {{ text/100 }}元
      </span>
      <a-tag  v-if="text==0" slot="state" slot-scope="text" color="#f50">
        {{ text | statusFilter }}
      </a-tag>

      <a-tag v-else slot="state" slot-scope="text" color="#2db7f5">
        {{ text | statusFilter }}
      </a-tag>

      <span slot="type" slot-scope="text">
        {{ text | chargeTypeFilter }}
      </span>

      <template slot="sort" slot-scope="text, record">
        <editable-cell :text="text" @change="onCellChange($event, record.id, 'sort')"/>
      </template>

      <span slot="beginTime" slot-scope="text,record">
        {{record.beginTime }} ~ {{record.endTime }}
      </span>



      <span slot="action" slot-scope="text, record">
        <template>
         <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
        </template>
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down"/>
          </a>
          <a-menu slot="overlay">

            <a-menu-item>
              <a @click="handleUpper(record)"> {{record.state ==0 ? '上架':'下架'}} </a>
            </a-menu-item>
            <a-menu-item>
              <a v-action:delete @click="handleDel(record)">删除</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>

  </a-card>
</template>

<script>
  import STable from '@/components/table/'
  import Edit from './Edit'
  import Add from './Add'
  import EditableCell from '@/components/table/EditableCell'
  import { selectList, updateState, selectAll,selectByCompanyId,Delete,updateSort } from '@/api/commodityService/commodity'
  // import { selectAllCompany } from '@/api/system/company'


  export default {
    components: {
      STable,
      Edit,
      EditableCell,
      Add
    },
    //--############  data() ###############-->
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        merchantList: [],
        description: '',
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        companys:[],
        code: [],
        treeData: [],
        // 表头
        columns: [
          {
            title: '商品图',
            dataIndex: 'productPicUrl',
            scopedSlots: { customRender: 'productPicUrl' }
          },
          // {
          //   title: 'ID轮播图取值',
          //   dataIndex: 'id'
          // },
          {
            title: '优惠券',
            dataIndex: 'name'
          },
          {
            title: '券额',
            dataIndex: 'value',
            scopedSlots: { customRender: 'value' }
          },
          {
            title: '总量',
            dataIndex: 'productCount'
          },
          {
            title: '排序',
            dataIndex: 'sort',
            scopedSlots: { customRender: 'sort' }
          },

          {
            title: '上架状态',
            dataIndex: 'state',
            scopedSlots: { customRender: 'state' }
          },
          // {
          //   title: '精品推荐',
          //   dataIndex: 'quality',
          //   scopedSlots: { customRender: 'quality' }
          // },
          {
            title: '有效期',
            dataIndex: 'beginTime',
            scopedSlots: { customRender: 'beginTime' },
            width: 160,
          },
          // {
          //   title: '结束日',
          //   dataIndex: 'endTime'
          // },
          {
            title: '操作',
            dataIndex: 'action',
            width: '140px',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return selectList(Object.assign(parameter, this.queryParam))
            .then(res => {
              return res.result
            })
        },
        selectedRowKeys: [],
        selectedRows: [],
        treeData:[]
      }
    },
    //--############  data() ###############-->
    created() {
      selectAll().then(res => { //商圈
        this.companys = res.result
      })
    },

    //--############  methods() ###############-->
    methods: {
      handleProvinceChange(value) { //查询商圈
        this.selectAllMerchant(value)
      },
      selectAllMerchant: function(companyId) {
        const _this = this
        selectByCompanyId(companyId).then(res => {
          if (res.code === 200) {
            if(res.result==null){
              return
            }
            _this.treeData = res.result
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      handleEdit(record) {
        this.$emit('onEdit', record)
      },
      handleAdd() {
        this.$emit('onAdd')
      },
      handleDel(row) {
        const _this = this
        this.$confirm({
          title: '警告',
          content: `真的要删除 ${row.name} 吗?`,
          okText: '删除',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            // 在这里调用删除接口
            Delete(row.id).then(res => {
              _this.$message.info(res.message)
              _this.$refs.table.refresh()
            })
          },
          onCancel() {
          }
        })
      },
      onCellChange (value, id, dataIndex) {
        const _this = this
        updateSort({id: id, sort:value})
          .then(res => {
            _this.$message.info(res.message)
            _this.$refs.table.refresh()
          })
      },

      handleUpper: function(row) {
        // 0未上架，1上架
        let state = 1
        if (row.state == 1) {
          state = 0
        } else {
          state = 1
        }
        const body = {
          id: row.id,
          state: state
        }
        console.log(body)
        updateState(body).then(res => {
          console.log('上架')
          if (res.code === 200) {
            this.$message.success('操作成功！')
            //刷新页面
            this.$refs.table.refresh()
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },

      // updateData:function(row){
      //   console.log("row.couponStockId",row.couponStockId)
      //   let body={
      //     couponStockId:row.couponStockId
      //   }
      //   updateData(body).then(res => {
      //     if (res.code === 200) {
      //       this.$message.success('操作成功！')
      //       //刷新页面
      //       this.$refs.table.refresh()
      //     } else {
      //       this.$notification.error({
      //         message: '错误',
      //         description: res.message,
      //         duration: 4
      //       })
      //     }
      //   })
      // },

      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },

    },
    filters: {
      statusFilter(state) {
        const statusMap = {
          0: '未上架',
          1: '已上架'
        }
        return statusMap[state]
      },
      chargeTypeFilter(type){
        const statusMap = {
          1: '免费优惠卷',
          2: '收费优惠卷',
          3: '积分兑换'
        }
        return statusMap[type]
      }
    }
    //--############  methods() ###############-->
  }
</script>
